import datetime
import json

from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.house.models import House
from apps.order.models import Order
from apps.users.models import User
from love_home.utils.response_code import RET
from love_home.utils.views import LoginRequiredJSONMixin


class HouseOrder(View):
    def post(self, request):
        '''预定房间'''
        user = request.user

        # 1 自定义变量-接收参数
        params = json.loads(request.body.decode())
        # 房屋ID
        house_id = params.get('house_id')
        # # 用户姓名
        # username = params.get('username')
        # 开始时间
        start_date_str = params.get('start_date')
        # 结束时间
        end_date_str = params.get('end_date')
        # 根据 username 创建 user对象
        # user = User.objects.get(username=username)
        days = ''

        # 2 校验参数
        if not all([house_id, start_date_str, end_date_str]):
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数错误'})

        try:
            # 校验用户输入住店时间和离店时间
            start_date = datetime.datetime.strptime(start_date_str, '%Y-%m-%d')
            end_date = datetime.datetime.strptime(end_date_str, '%Y-%m-%d')
            if not start_date < end_date:
                return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数错误'})

                # 计算入住天数
            days = (end_date - start_date).days
            # print(days)
            # print(type(days))
        except Exception as e:
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数错误'})

        # 3 校验查询房屋是否存在
        try:
            house = House.objects.get(id=house_id)
            print(house.title)
        except Exception as e:
            return http.JsonResponse({'errno': RET.NODATA, 'errmsg': "房屋不存在"})

        # 4 判断当前是房主还是房客， 房东不能预定
        if house.user_id == user.pk:
            return http.JsonResponse({'errno': RET.ROLEERR, 'errmsg': "不能预订自已的房屋"})

        # 5 查询判断是否有冲突的订单
        order_count = Order.objects.filter(house_id=house_id, begin_date=start_date, end_date=end_date).count()

        if order_count > 0:
            return http.JsonResponse({'errno': RET.DATAERR, 'errmsg': "该房屋已被预订"})

        # 6 进行下单
        try:
            order_add = Order.objects.create(user=user, house=house, begin_date=start_date,
                                             end_date=end_date, days=days, house_price=house.price,
                                             amount=days * house.price)
            # print(order_add)
        except Exception as e:
            print(e)
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "生成订单失败"})

        # 7  给前台返回下单结果

        return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK", 'data': {"order_id": 1}})

    def get(self, request):
        ''' 查询客户订单API（身份：房东）/我的订单（身份：房客） '''
        ''' role   string
            required 角色类型：[custom: 房客，landlord：房东]
        '''
        # 自定义变量-测试用
        # username = 'zhangsan'
        # user = User.objects.get(username='zhangsan')
        user = request.user

        # 接收参数
        role = request.GET.get('role')  # 接收角色

        # 判断空，判角色
        if not all([role, user]):
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数错误'})
        # 判断身份是否在角色里面
        if role not in ('custom', 'landlord'):
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数错误'})

        # 构建orders 数据
        try:
            if 'custom' == role:  # 房客查询订单
                orders = Order.objects.filter(user=user).order_by('-create_time')
            elif 'landlord' == role:  # 房东查询订单
                # 先查询 User 和 house 中有没有发布的房源，
                houses = House.objects.filter(user=user)
                # 取出房屋ID
                house_ids = []
                for houses.pk in houses:
                    house_ids.append(houses.pk)
                    print(houses.pk)

                orders = Order.objects.filter(house_id__in=house_ids).order_by('-create_time')
        except Exception as e:
            print(e)
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "数据查询错误"})
        try:

            orders_list = []
            for order in orders:
                orders_list.append({
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.create_time.strftime('%Y-%m-%d'),
                    "days": order.days,
                    "end_date": order.end_date.strftime('%Y-%m-%d'),
                    "img_url": order.house.index_image_url,
                    "order_id": order.pk,
                    "start_date": order.begin_date.strftime("%Y-%m-%d"),
                    "status": order.status,
                    "title": order.house.title
                })
                print(orders_list)
            return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK", 'data': {"orders": orders_list}})
        except Exception as e:
            print(e)
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "数据查询错误"})

    def put(self, request):
        '''
        1 接收参数
        2 通过 order_id 找到 订单的状态
        3 修改订单状态
        4 保存
        '''
        user = request.user
        order_json = json.loads(request.body.decode())
        order_id = order_json.get('order_id')  # 接收order_id
        action = order_json.get('action')  # 接收操作类型：[accept: 接单，reject：拒单]
        reason = order_json.get('reason')  # 接收 拒单时，需要填写拒单原因

        # 校验
        if not all([order_id,action]):
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数错误'})

        # 通过 order_id 找到 订单
        try:
            order = Order.objects.get(pk=order_id, status='WAIT_ACCEPT')
        except Exception as e:
            return http.JsonResponse({'errno': RET.NODATA, 'errmsg': "未查询到订单"})

        # 修改订单
        if 'accept' == action:
            order.status = 'WAIT_COMMENT'  # 接单待评价

        elif 'reject' == action:
            order.status = 'REJECTED'  # 拒单

            if not reason:
                return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "请填写拒单原因"})
            # 保存拒单原因
            order.comment = reason

        try:
            order.save()
        except Exception as e:
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "保存数据失败"})

        return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK"})


class HouseComment(LoginRequiredJSONMixin,View):
    def put(self, request):
        '''订单评论'''
        # 1 接收参数 comment 评论内容，  order_id
        # 2 校验
        # 3 入库评论内容
        user = request.user
        comment_data = json.loads(request.body.decode())
        order_id = comment_data.get('order_id')
        comment = comment_data.get('comment')

        # 校验
        if not all([order_id, comment]):
            return http.JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数错误"})

        # 入库
        try:
            order_comment_datas = Order.objects.get(pk=order_id)
            order_comment_datas.comment = comment
            order_comment_datas.status = 'COMPLETE'
            order_comment_datas.save()
        except Exception as e:
            return http.JsonResponse({'errno': RET.DBERR, 'errmsg': "保存数据失败"})

        return http.JsonResponse({'errno': RET.OK, 'errmsg': "OK"})
